// pages/user_management_add/user_management_add.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    auth: {},
    userId: '',

    toggle: {
      0: false,
      1: false,
    },

    fieldList: [
      { field_id: 'employee', label: '员工', type: 'picklist', is_null: false, optionList: [], optionId: 'tel', optionName: 'job_name', },
      { field_id: 'role_id', label: '角色', type: 'picklist', is_null: false, optionList: [], optionId: 'id', optionName: 'name', },

      { field_id: 'user_id', label: '账号', type: 'text', is_null: true, },
      { field_id: 'password', label: '密码', type: 'password', is_null: false, plc: '请输入6位以上的大小写字母数字', },
    ],
    validFlag: false,             // 验证标识
    validData: {},                // 验证表单项
    formData: {
      employee: '',
      password: '',
      role_id: '',
      user_id: '',
      username: '',
    },

    disObj: {
      user_id: true,
    },
  },

  toggleSub(e) {
    let { i, } = e.currentTarget.dataset,
        { toggle, } = this.data
    toggle[i] = !toggle[i]
    this.setData({
      toggle,
    })
  },

  changeIpt(e) {
    let { field, val, } = e.detail,
        { field_id, optionList, optionId, optionName, } = field,
        { formData, } = this.data,
        oldVal = formData[field_id]

    if(['employee'].includes(field_id)) {
      let selItem = null
      optionList.some(opt => {
        if(opt[optionId] === val) {
          selItem = opt
          return true
        }
      })
      formData.user_id = val
      if(selItem) formData.user_name = selItem.job_name
    }
    if(formData[field_id] !== undefined) {
      formData[field_id] = val
    }

    if(oldVal !== val) {
      this.setData({
        formData,
      })
    }
  },
  // 记录验证表单项
  validIpt(e) {
    let { validData, } = this.data
    this.data.validData = {
      ...validData,
      ...e.detail,
    }
  },
  // 保存/保存并新增
  saveData(e) {
    let { auth, userId, } = this.data,
        msg = !auth.tableAppend ? '抱歉，您没有权限新增该模块数据' : ''
    if(userId) msg = !auth.tableEdit ? '抱歉，您没有权限编辑该模块数据' : ''
    if(msg) {
      wx.$toast(msg)
      return
    }

    let { reset, } = e.currentTarget.dataset
    this.data.validData = {}
    this.setData({
      validFlag: !this.data.validFlag,
    })

    let { fieldList, validData, formData, } = this.data
    wx.$validForm(fieldList, validData).then(valid => {
      if(valid) {
        let reg = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[A-Za-z\d]{6,}$/   // 至少包含大小写字母数字的6位以上
        if (!reg.test(formData.password)) {
          wx.$toast('请输入至少6位以上包含大小写字母和数字的密码！')
          return
        }
        this.saveUserData(formData).then(res => {
          wx.$toast('保存成功！', 2000).then(() => {
            if(reset) {
              wx.redirectTo({
                url: '../user_management_add/user_management_add',
              })
            } else {  // 保存
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        })
      } else {
        wx.$toast('必填项不能为空！')
      }
    })
  },

  // 接口
  ready() {
    // 获取员工、角色 选项列表
    let p0 = this.getOptionList(0, 'employee', 3, 'BaseTable/query_all_employee_inf', { limit: 0, oby: 'input_time', page: 1, }),
        p1 = this.getOptionList(1, 'role_id', 3, 'BaseTable/select_role', {})
    return new Promise((resolve, reject) => {
      Promise.all([p0, p1,]).then(res => {
        let fieldList = this.data.fieldList,
            obj = {}
        res.forEach((item, i) => {
          obj = { ...obj, ...item, }
        })
        fieldList.forEach(item => {
          let key = item.field_id
          if(obj[key]) item.optionList = obj[key]
        })
        this.setData({
          fieldList,
        })

        resolve()
      })
    })
  },
  getOptionList() {
    return new Promise((resolve, reject) => {
      let [ method, key, v, url, params, ] = arguments
      let request = method ? wx.$get : wx.$post
      request(v, url, params).then(res => {
        if(res.errcode !== 0) return
        let rows = res.data.row
        rows = rows.flat()
        resolve(key ? { [key]: rows, } : rows)
      })
    })
  },
  getUserData() {
    if(!this.data.auth.tableSee) {
      wx.$toast('抱歉，您没有权限查看该模块')
      return
    }
    let post = {
      page: 1,
      limit: 1,
      oby: 'input_time desc',
      SearchWhere: [{
        CompareValue: this.data.userId,
        CompareWith: 'user_id',
        Operator: '=',
        or: 0,
      }],
    }
    wx.$post(3, 'BaseTable/query_all_user', post).then(res => {
      if(res.errcode !== 0) return
      let row = res.data.row[0],
          { user_id, role_id, password, username, } = row,
          formData = {
            employee: user_id,
            password,
            role_id,
            user_id,
            username,
          }
      this.setData({
        formData,
      })
    })
  },
  saveUserData(post) {
    let url = this.data.userId ? 'BaseTable/alter_user' : 'BaseTable/create_user'
    wx.showLoading({ mask: true, })
    return new Promise((resolve, reject) => {
      wx.$post(3, url, post).then(res => {
        wx.hideLoading()
        if(res.errcode !== 0) return
        resolve()
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.$setBarTitle();
    let { entity, id, } = options,
        auth = await wx.$getAuth(entity)
    this.data.auth = auth
    this.ready().then(res => {
      if(id) {
        this.setData({
          userId: id,
        })
        this.getUserData()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})
